<template>
  <div class="box">
    <h1 class="title">字段规则配置</h1>
    <!-- <el-row>
      <el-col>
        <el-button class="add-btn" size="small" @click="addRules">新增规则</el-button>
      </el-col>
    </el-row> -->
    <el-table
      ref="multipleTable"
      :data="data.MappingData"
      tooltip-effect="dark"
      style="width: 100%;overflow-y: auto;max-height:500px;"
      border
    >
      <el-table-column
        prop="column"
        label="字段"
        width="auto"
      />
      <el-table-column prop="readRule" label="读取规则" width="auto">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEditCode(scope,'readRule')">编辑</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="writeRule" label="写入规则" width="auto">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEditCode(scope,'writeRule')">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-col style="text-align: right">
        <el-button class="add-btn" size="small" @click="previewResult">预览读写结果</el-button>
      </el-col>
    </el-row>

    <el-dialog
      title="规则编辑"
      :visible.sync="codeDialogVisible"
      width="50%"
    >
      <el-row style="margin-bottom: 10px;">
        <el-col style="text-align: right">
          <span>规则类型：</span>
          <el-select
            v-model="rulesForm.ruleType"
            placeholder="请选择规则类型"
          >
            <el-option
              v-for="item in dict.type.data_sync_column_ruletype"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
      </el-row>

      <codeEditor
        :key="upDataCodeKey"
        ref="codeEditor"
        :code-data="rulesForm.ruleContent"
        value-code-lang="groovy"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="codeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="codeSave">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="读写脚本结果预览"
      :visible.sync="previewDialogVisible"
      width="60%"
    >
      <div>
        <el-menu v-model="activeIndex" :default-active="activeIndex" mode="horizontal" @select="handleSelect">
          <el-menu-item index="1">读取预览</el-menu-item>
          <el-menu-item index="2">写入预览</el-menu-item>
        </el-menu>
        <el-table
          class="change-height"
          :data="previewData[activeIndex === '1' ? 'readRows' : 'writeRows']"
          :style="{ maxHeight: '500px',overflow:'auto' }"
          border
        >
          <el-table-column type="index" />
          <el-table-column v-for="item in previewData.columns" :key="item.columnName" :prop="item.columnName" :label="item.columnLabel">
            <template slot="header" slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="item.columnTypeName" placement="top">
                <span>{{ item.columnLabel }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="previewDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import codeEditor from '@/components/CodeEditor/index.vue'
import { sqlTaskExecuteSql, sqlReadPreview } from '@/api/console/executeSql'
import Vue from 'vue'

export default {
  name: 'TaskSelectMigrationThree',
  components: { codeEditor },
  dicts: ['data_sync_column_ruletype'],
  // eslint-disable-next-line vue/require-prop-types
  props: ['data'],

  data: function() {
    return {
      previewDialogVisible: false,
      codeDialogVisible: false,
      rulesForm: {
        ruleType: '',
        ruleContent: '',
        rule: ''
      },
      rules: {},
      currentData: {
        index: null,
        name: ''
      },
      upDataCodeKey: '',
      activeIndex: '1',
      previewData: {
        readRows: [],
        writeRows: [],
        columns: null
      }
    }
  },
  created() {

  },
  mounted() {
    if (!this.$props.data.MappingData) {
      this.initTable()
    }
  },
  methods: {
    handleSelect(_v) {
      this.activeIndex = _v
    },
    async previewResult() {
      const { sql, dataSourceValue, MappingData } = this.$props.data
      let res = await sqlReadPreview({
        datasourceId: dataSourceValue,
        sqlContext: sql,
        params: {
          mapping: MappingData
        }
      })
      if (res.data.code !== 200) {
        return this.$message.error(res.data.msg)
      }
      res = res.data.data
      console.log(res)

      this.previewData.columns = res.columns
      res.columns.forEach((f, index) => {
        res.readRows.forEach((j, i) => {
          this.previewData.readRows[i] = {
            ...this.previewData.readRows[i],
            [f.columnName]: j[index]
          }
        })
        res.writeRows.forEach((j, i) => {
          this.previewData.writeRows[i] = {
            ...this.previewData.writeRows[i],
            [f.columnName]: j[index]
          }
        })
      })
      this.previewDialogVisible = true
    },
    async initTable() {
      const { sql, dataSourceValue } = this.$props.data
      const tableData = []
      const res = await sqlTaskExecuteSql({
        datasourceId: dataSourceValue,
        sqlContext: sql,
        databaseName: '',
        pageSize: 999
      })
      if (!res.data.data.columns || !res.data.data.rows) {
        return this.$message.warning('请先写入正确的SQL')
      }
      let dict = await this.getDicts('data_sync_column_ruletype')
      dict = dict.data.find(f => f.dictValue === 'DEFAULT')

      res.data.data.columns.forEach(f => {
        tableData.push({
          column: f.columnName,
          readRule: {
            rule: '',
            ruleType: dict.dictValue,
            ruleContent: null
          },
          writeRule: {
            rule: '',
            ruleType: dict.dictValue,
            ruleContent: null
          }
        })
      })
      Vue.set(this.$props.data, 'MappingData', tableData)
    },
    handleApply(scope) {
      if (scope.row.column.length < 1 || scope.row.redsRules.length < 1 || scope.row.writeRules.length < 1) {
        return this.$message.warning('请填写完整规则')
      }
    },
    addRules() {
      this.tableData.push({
        column: '',
        redsRules: '',
        writeRules: ''
      })
    },
    handleDelete(scope) {
      this.tableData.splice(scope.$index, 1)
    },
    handleEditCode(scope, type) {
      const { ruleContent, ruleType, rule } = scope.row[type]
      this.rulesForm = {
        ruleType,
        ruleContent,
        rule
      }
      this.upDataCodeKey = Math.random()

      this.currentData = {
        index: scope.$index,
        type
      }
      this.codeDialogVisible = true
    },
    codeSave() {
      const that = this
      this.$props.data.MappingData[this.currentData.index][this.currentData.type] = {
        ruleType: that.rulesForm.ruleType,
        ruleContent: this.$refs.codeEditor._data.content,
        rule: that.rulesForm.rule
      }
      // this.$props.data.MappingData[this.currentData.index][this.currentData.type] =
      this.codeDialogVisible = false
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table .el-table__header-wrapper th {
  background-color: #fff;
}

.box{
  width: 75%;
  margin: 0 auto;

  .add-btn{
    background: rgb(86, 100, 245);
    color:#fff;
    margin:10px 0 15px 0;
    text-align: center;
    border-radius: 7px;
  }

  .title {
    color: #333;
    font-size: 22px;
    line-height: 1.25;
    font-family: alimama, webfont-notdef;
    font-size: 18px;
    box-sizing: border-box;
    font-weight: 600;
    text-align: left;
  }
}
</style>
